$(function () {
    layui.use('table', function () {
        const table = layui.table;

        //根据参数名获取参数值
        function getQueryStringByName(name) {
            const result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
            if (result == null || result.length < 1) {
                return "";
            }
            return result[1];
        }

        var data = [];

        initTable()

        function getDataRemote() {
            $.ajax({
                url: "/KnowledgeManager/seeKnowledge?knowManagerId=" + getQueryStringByName('id'),
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify({page: 1, limit: 100, search: {knowManagerId: getQueryStringByName('id')},}),
                success: result => {
                    var resultObject = JSON.parse(result)
                    data.push.apply(data, resultObject.data)
                    if ((isAdd())) {
                        data = []
                    }
                    initTable();
                },
                error: xhr => {
                    layer.msg('获得数据失败')
                }
            })
        }


        function initTable() {
            var nameInput = $('#content > div.table-cont > table:nth-child(1) > tbody > tr > td:nth-child(2) > input[type=text]')
            var nameParam = getQueryStringByName('name')
            nameParam = decodeURI(nameParam)
            if (!!nameParam) {
                nameInput.val(nameParam);
                nameInput.attr('disabled', 'disabled')
                var breadScrumb = $('#location');
                breadScrumb.html(breadScrumb.html().replace("添加", "编辑"))
            }
            table.render({
                elem: '#add-point-table',
                method: 'post',
                data: data,
                contentType: 'application/json;charset=utf-8',
                page: true,
                cols: [
                    [
                        {field: 'name', title: '岗位名称', width: '15%', rowspan: 2},
                        {title: '单项选择题', width: '10%', colspan: 2, align: 'center'},
                        {title: '不定项选择题', width: '10%', colspan: 2, align: 'center'},
                        {title: '填空题', width: '10%', colspan: 2, align: 'center'},
                        {title: '判断正误题', width: '10%', colspan: 2, align: 'center'},
                        {title: '简答题', width: '10%', colspan: 2, align: 'center'},
                        {title: '综合题', width: '10%', colspan: 2, align: 'center'},
                        {
                            title: '<button type="button" class="layui-btn layui-btn-xs" style="height: 22px !important;line-height: 22px;padding: 0 5px;font-size: 12px;display: inline-block;white-space: nowrap;text-align: center;border: none;border-radius: 12px;margin: 2px 0 0 5px;cursor: pointer;outline: 0;-webkit-appearance: none;-webkit-transition: all .3s;box-sizing: border-box;width: 22px;background-color: royalblue !important; color: whitesmoke !important;">+</button>',
                            width: '5%', rowspan: 2, toolbar: '#toolbar',
                        },
                    ],
                    [
                        {field: 'singleacount', title: '标准数量', edit: 'text'},
                        {field: 'singlescount', title: '抽题数量', edit: 'text'},
                        {field: 'indefiacount', title: '标准数量', edit: 'text'},
                        {field: 'indefiscount', title: '抽题数量', edit: 'text'},
                        {field: 'fillacount', title: '标准数量', edit: 'text'},
                        {field: 'fillscount', title: '抽题数量', edit: 'text'},
                        {field: 'judgeacount', title: '标准数量', edit: 'text'},
                        {field: 'judgescount', title: '抽题数量', edit: 'text'},
                        {field: 'answeracount', title: '标准数量', edit: 'text'},
                        {field: 'answerscount', title: '抽题数量', edit: 'text'},
                        {field: 'synthacount', title: '标准数量', edit: 'text'},
                        {field: 'synthscount', title: '抽题数量', edit: 'text'},
                    ],
                ],
                where: {
                    search: {
                        'knowManagerId': getQueryStringByName('id'),
                    },
                },
                parseData: parseLimitResult,
                done: function (result, curr, count) {
                    // data.push.apply(data, result.data)
                    data = result.data
                    addButtonClickBind()
                }
            })
        }

        function isAdd() {
            return !Boolean(getQueryStringByName('id'))
        }

        function tableReload() {
            table.reload('add-point-table', {
                url: undefined,
                data: data,
            })
        }

        function parseLimitResult(value) {
            return {
                "code": value.status - 1,
                "msg": value.msg,
                "count": value.page.total,
                "data": value.data,
            }
        }

        //监听工具条
        table.on('tool(add-point-table)', function (obj) {
            var iData = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;

            if (layEvent === 'del') {
                data = data.filter(value => value.name !== iData.name)
                tr.remove()
            }
        })

        //监听表格编辑
        table.on('edit(add-point-table)', function (obj) {
            // data.filter(obj => obj.id === 1)[0][obj.field] = obj.value;
        });

        //保存按钮
        $('#content > div.btnbar > button.save').off('click').on('click', function () {
            var kName = $("#content > div.table-cont > table:nth-child(1) > tbody > tr > td:nth-child(2) > input[type=text]").val();
            if (!kName) {
                layer.msg('请输入知识点名称');
                return;
            }
            if (data.length === 0) {
                layer.msg('知识点为空');
                return;
            }
            var url;
            url = "/KnowledgeManager/addKnowledge" + '?knowledgeName=' + kName + '&position=';

            //删除LAY_TABLE_INDEX
            var dataCopy = data.concat().map(function (value) {
                if (value.LAY_TABLE_INDEX !== undefined)
                    delete value.LAY_TABLE_INDEX;
                if (value.kname !== undefined)
                    delete value.kname
                return value
            })
            $.ajax({
                url: url,
                type: 'POST',
                data: JSON.stringify(dataCopy),
                contentType: 'application/json',
                success: function (data) {
                    layer.msg('添加成功', {icon: 1})
                },
                error: function (data) {
                    layer.msg('知识点添加失败', {icon: 2})
                }
            });
            // })

        })

        table.on('toolbar(add-point-table)', function (obj) {
            console.log(obj)
        })

        //加号按钮
        function addButtonClickBind() {
            $('#content > div.table-cont > div > div.layui-table-box > div.layui-table-header > table > thead > tr:nth-child(1) > th:nth-child(8)').on('click', function () {
                var index = layer.open({
                    type: 1,
                    title: '选择岗位',
                    content: $('#add-position'),
                    offset: '30px',
                    area: ['500px', '600px'],
                })

                const table = layui.table;
                table.render({
                    elem: '#position-table',
                    url: '/SysAdmin/getJobsLayuiJson?code=&name=&deptcode=&' + $("#positionSearchbox").serialize(), //数据接口
                    page: true,
                    cols: [
                        [
                            {type: 'checkbox', fixed: 'left', width: 50},
                            {field: 'name', title: '岗位名称'},
                        ],
                    ],
                })

                //选择岗位保存按钮
                $('#add-position > div.btnbar > button').off('click').on('click', function () {
                    var checkStatus = table.checkStatus('position-table');
                    checkStatus.data.filter(d1 => data.map(d2 => d2.name).indexOf(d1.name) < 0).forEach(d3 => {
                        data.push({
                            'name': d3.name, 'answeracount': 0, 'answerscount': 0, 'fillacount': 0, 'fillscount': 0,
                            'indefiacount': 0, 'indefiscount': 0, 'judgeacount': 0, 'judgescount': 0,
                            'singleacount': 0, 'singlescount': 0, 'synthacount': 0, 'synthscount': 0,
                        })
                    })

                    tableReload();
                });
            })
        }
    })
})
